#include <config.h>
#include <encoding_manager.h>
#include <string.h>

static int Utf8isSupported(unsigned char *pucFileName)
{
	const char aStrUtf8Head[] = {0xEF, 0xBB, 0xBF, 0};

	if(strncmp(aStrUtf8Head, (const char *)pucFileName, 2) == 0)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

static int GetPreOneNum(unsigned char ucVal)
{
	int i, j;
	for(i = 7; i >= 0; i--)
	{
		if(ucVal & (1<<i))
			j++;
		else
			break;
	}
	return j;
}

static int Utf8GetCodeFrmBuffer(unsigned char *pucBufStart, unsigned char *pucBufEnd, unsigned int *pdwCode)
{
	unsigned char ucVal;
	unsigned int dwSum = 0;
	int iNum;
	int i;

	if(pucBufStart >= pucBufEnd)
	{
		return 0;
	}

	ucVal = pucBufStart[0];
	iNum = GetPreOneNum(pucBufStart[0]);

	if(pucBufStart + iNum >= pucBufEnd)
	{
		return 0;
	}

	if(iNum == 0)
	{
		*pdwCode = pucBufStart[0];
		return 1;
	}
	else
	{
		ucVal = ucVal << iNum;
		ucVal = ucVal >> iNum;
		dwSum += ucVal;
		for(i = 1; i < iNum; i++)
		{
			ucVal = (pucBufStart[i]) & 0x3f;
			dwSum = dwSum << 6;
			dwSum += ucVal;
		}
		*pdwCode = dwSum;
		return iNum;
	}
}


static T_EncodingOpr g_tUtf8EncodingOpr = {
	.name = "utf8",
	.iHeadLen    = 3,
	.isSupported = Utf8isSupported,
	.GetCodeFrmBuffer = Utf8GetCodeFrmBuffer,
};

int Utf8Register(void)
{
	AddFontOprForEncoding(&g_tUtf8EncodingOpr, GetFontOpr("freetype"));
	AddFontOprForEncoding(&g_tUtf8EncodingOpr, GetFontOpr("ascii"));
	return RegisterEncodingOpr(&g_tUtf8EncodingOpr);
}




